<!-- purchaseDetailPage.vue -->
<template>
    <!-- 在页面顶部或底部添加加载遮罩 -->
    <div v-loading="submitting" class="purchase-contract-detail-container">
        <div class="purchase-contract-detail-container">
            <!-- Document Information Group -->
            <el-card class="info-card" shadow="never">
                <template #header>
                    <div class="card-header">
                        <div class="title-wrapper">
                            <span class="title-text">单据信息</span>
                            <span v-if="multiStoreMode" class="store-name">{{ purchaseContract.storeName
                            }}</span>
                            <el-tag v-if="!this.editMode"
                                :type="purchaseContract.status.code === CommonOrderStatus.Passed.code ? 'success' : 'info'"
                                size="small" class="status-tag">
                                {{ purchaseContract.status.name }}
                            </el-tag>
                        </div>
                        <!-- Action Buttons -->
                        <div class="action-buttons" v-if="!this.editMode">
                            <el-button plain @click="handleCopy">
                                <el-icon>
                                    <CopyDocument />
                                </el-icon> 复制
                            </el-button>
                            <el-button plain @click="handlePrint" style="margin-right: 20px">
                                <el-icon>
                                    <Printer />
                                </el-icon> 打印
                            </el-button>
                            <el-button v-if="PurchaseContract.hasMetalOrderEditPermission()" type="primary" plain
                                @click="handleEdit">
                                <el-icon>
                                    <Edit />
                                </el-icon> 编辑
                            </el-button>
                            <el-button v-if="PurchaseContract.hasMetalOrderEditPermission()" type="danger" plain
                                @click="handleDelete">
                                <el-icon>
                                    <Delete />
                                </el-icon> 删除
                            </el-button>
                        </div>
                    </div>
                </template>
                <el-form ref="ruleFormRef" :model="formData" label-width="100px">
                    <el-row :gutter="20">
                        <!-- 
                        <el-col :span="6">
                            <input-widget-web v-model="formData.title" label="单据标题" prop="title"
                                :readonly="!this.editMode" />
                        </el-col>
                        -->
                        <el-col v-if="!this.editMode" :span="6">
                            <input-widget-web v-model="formData.docCode" label="单据编号" prop="docCode"
                                :readonly="!this.editMode" />
                        </el-col>

                        <el-col :span="6">
                            <partner-select v-model="formData.targetObject" label="供应商" prop="targetObject"
                                :readonly="!this.editMode" initialPartnerType="supplier"
                                :rules="[{ required: true, message: '请选择供应商', trigger: 'blur' }]"
                                :basicUiAction="basicUiAction" @update:model-value="val => {
                                    updateTargetObject(val);
                                }" />
                        </el-col>
                        <!--
                        <el-col :span="6">
                            <partner-select v-model="formData.targetObject" label="供应商" prop="targetObject"
                                :readonly="!this.editMode" initialPartnerType="all"
                                :targetObjectPlatformType="TargetObjectPlatformType.TUserCreated"
                                :rules="[{ required: true, message: '请选择供应商', trigger: 'blur' }]"
                                :basicUiAction="basicUiAction" />
                        </el-col>
                        -->

                        <el-col v-if="supportMultyWarehouse" :span="6">
                            <warehouse-select v-model="formData.warehouse" label="仓库" prop="warehouse"
                                :readonly="!this.editMode" :inventoryUiAction="inventoryUiAction" />
                        </el-col>

                        <el-col :span="6">
                            <date-time-select v-model="formData.operateDate" label="回购日期" prop="operateDate"
                                :readonly="!this.editMode" type="datetime" />
                        </el-col>

                        <el-col :span="6">
                            <employee-select v-model="formData.operator" label="经办人" prop="operator"
                                :readonly="!this.editMode" :enterpriseMgtUiAction="enterpriseMgtUiAction" />
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>

            <!-- Purchase Items Group -->
            <el-card class="items-card" shadow="never">
                <template #header>
                    <div class="card-header">
                        <div class="title-wrapper">
                            <div class="summary-container">
                                <span class="title-text">回购商品</span>
                            </div>
                            <!-- 添加和删除按钮 
                            <div v-if="editMode" class="action-buttons">
                                <el-button type="primary" size="small" @click="handleAddCommodity">
                                    添加商品
                                </el-button>
                                <el-button type="danger" size="small" @click="handleDeleteSelectedCommodities">
                                    删除商品
                                </el-button>
                            </div>
                            -->
                        </div>
                    </div>
                </template>

                <el-table :data="purchaseContract.commmodityList" style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <!-- 勾选列 -->
                    <el-table-column type="selection" width="55" v-if="editMode" />

                    <el-table-column label="品名" width="180">
                        <template #default="scope">
                            <SubcommoditySelect :model-value="scope.row.commodity"
                                :commodityUiActionProps="commodityUiAction" :readonly="!editMode"
                                :filter-props="metalSubcommodityFilter" @update:model-value="val => {
                                    // 设置商品
                                    scope.row.commodity = val;
                                }" />
                        </template>
                    </el-table-column>
                    <!-- 
                    <el-table-column label="单位" width="80">
                        <template #default="scope">
                            {{ scope.row.commodity.unit?.name || '-' }}
                        </template>
                    </el-table-column> -->

                    <el-table-column label="金价" align="center" width="120">
                        <template #default="scope">
                            <input-cell v-if="scope.row.commodity" :readonly="!editMode"
                                :model-value="scope.row.referPrice?.value || 0" :numberMode="true"
                                :precision="fundPrecision" @update:model-value="val => {
                                    scope.row.referPrice = new CsFundDouble(val, fundPrecision);
                                    purchaseContract.calculatePriceAndQuantity();
                                }" />
                        </template>
                    </el-table-column>

                    <el-table-column label="重量" align="center" width="120">
                        <template #default="scope">
                            <input-cell v-if="scope.row.commodity" :readonly="!editMode"
                                :model-value="scope.row.count.value" :numberMode="true" :precision="countPrecision"
                                @update:model-value="val => {
                                    scope.row.setCount(new CsDouble(val, countPrecision));
                                    //testLog(scope.row);
                                    purchaseContract.calculatePriceAndQuantity();
                                }" />
                        </template>
                    </el-table-column>

                    <el-table-column label="成色" align="center" width="160">
                        <template #default="scope">
                            <MetalFinessInputCell v-if="scope.row.commodity" :readonly="!editMode"
                                :model-value="scope.row.discount.value * 10"
                                @update:model-value="val => { scope.row.discount = new CsDouble(val / 10, disCountRation); purchaseContract.calculatePriceAndQuantity(); }" />
                        </template>
                    </el-table-column>

                    <el-table-column label="折后重量" align="center" width="120">
                        <template #header>
                            <span>折后重量</span>
                            <el-tooltip :content="discountWeightHint" placement="top" raw-content>
                                <el-icon style="margin-left: 5px; cursor: pointer;">
                                    <QuestionFilled />
                                </el-icon>
                            </el-tooltip>
                        </template>
                        <template #default="scope">
                            <template
                                v-if="scope.row.commodity && scope.row.metalPurchaseTradeMode?.code === MetalPurchaseTradeMode.SettledPrice.code">
                                <!-- Read-only mode  
                                <span>--</span>
                                 -->
                                <span>{{ scope.row.countAfterDiscount.value }}</span>
                            </template>
                            <template v-else>
                                <input-cell v-if="scope.row.commodity" :readonly="true"
                                    :model-value="scope.row.countAfterDiscount.value" :numberMode="true"
                                    :precision="countPrecision"
                                    @update:model-value="val => { scope.row.setCountAfterDiscount(new CsDouble(val, countPrecision)); purchaseContract.calculatePriceAndQuantity(); }" />
                            </template>
                        </template>
                    </el-table-column>

                    <el-table-column label="单价(元/g)" align="center" width="120">
                        <template #header>
                            <span>单价(元/g)</span>
                            <el-tooltip :content="discountPriceHint" placement="top" raw-content>
                                <el-icon style="margin-left: 5px; cursor: pointer;">
                                    <QuestionFilled />
                                </el-icon>
                            </el-tooltip>
                        </template>
                        <template #default="scope">
                            <template
                                v-if="scope.row.metalPurchaseTradeMode?.code === MetalPurchaseTradeMode.SettleMetal.code">
                                <!-- Read-only mode -->
                                <span>--</span>
                            </template>
                            <template v-else>
                                <input-cell v-if="scope.row.commodity" :readonly="true"
                                    :model-value="scope.row.singlePriceAfterTax.value" :numberMode="true"
                                    :precision="fundPrecision" @update:model-value="val => {
                                        scope.row.setSinglePriceAfterTax(new CsFundDouble(val, fundPrecision));
                                        purchaseContract.calculatePriceAndQuantity();
                                    }" />
                            </template>
                        </template>
                    </el-table-column>

                    <el-table-column label="应付金额" align="center" width="120">
                        <template #default="scope">
                            <template
                                v-if="scope.row.metalPurchaseTradeMode?.code === MetalPurchaseTradeMode.SettleMetal.code">
                                <!-- Read-only mode -->
                                <span>--</span>
                            </template>
                            <template v-else>
                                <input-cell v-if="scope.row.commodity" :readonly="true"
                                    :model-value="scope.row.batchPriceWithTax.value" :numberMode="true"
                                    :precision="fundPrecision" @update:model-value="val => {
                                        scope.row.setBatchPriceWithTax(new CsFundDouble(val, fundPrecision));
                                        purchaseContract.calculatePriceAndQuantity();
                                    }" />
                            </template>
                        </template>
                    </el-table-column>

                    <el-table-column label="模式" align="center" width="150">
                        <template #header>
                            <span>模式</span>
                            <el-tooltip :content="tradeModeHint" placement="top" raw-content>
                                <el-icon style="margin-left: 5px; cursor: pointer;">
                                    <QuestionFilled />
                                </el-icon>
                            </el-tooltip>
                        </template>
                        <template #default="scope">
                            <template v-if="!editMode">
                                <!-- Read-only mode -->
                                <span v-if="scope.row.metalPurchaseTradeMode">
                                    {{ scope.row.metalPurchaseTradeMode.name }}
                                </span>
                            </template>
                            <template v-else>
                                <!-- Edit mode -->
                                <el-select v-if="scope.row.commodity"
                                    :model-value="scope.row.metalPurchaseTradeMode?.code" placeholder="请选择模式" @change="val => {
                                        handleModeSelect(scope.row, val);
                                    }" style="width: 100%">
                                    <el-option v-for="mode in metalPurchaseTradeModes" :key="mode.code"
                                        :label="mode.name" :value="mode.code">
                                    </el-option>
                                </el-select>
                            </template>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" width="100" v-if="editMode">
                        <template #default="scope">
                            <el-button v-if="scope.row.commodity" link size="small" @click="handleDeleteRow(scope.row)"
                                style="color: #f56c6c;">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>

            <el-row :gutter="16" class="summary-row">
                <el-col :span="12">
                    <el-card class="amount-summary-card" shadow="never">
                        <template #header>
                            <div class="card-header">
                                <div class="title-wrapper">
                                    <span class="title-text">金额汇总</span>
                                </div>
                            </div>
                        </template>



                        <!-- Add this section after the "贵金属信息" title -->
                        <div style="margin: 4px 0; padding-top: 0px; padding-bottom: 8px;" class="amount-item">
                            <span class="label right-align"
                                style="font-size: 15px; font-weight: bold; color: #606266;">结价信息</span>
                        </div>

                        <div class="amount-summary-content">
                            <div class="amount-item">
                                <span class="label right-align">商品金额:</span>
                                <span class="value left-align">{{
                                    formatCurrency(purchaseContract.commodityPriceWithTax.value)
                                    }}</span>
                            </div>
                        <!-- 
                            <div class="amount-item">
                                <span class="label right-align">其他费用(扣):</span>
                                <div class="value left-align">
                                    <input-cell :width="'200px'" :readonlyWidth="'200px'" :readonly="true"
                                        :model-value="purchaseContract.otherFundsLessPrice.value.value"
                                        :numberMode="true" :precision="fundPrecision" />
                                    <el-button v-if="editMode" style="margin-left: 8px;" type="primary" size="small"
                                        class="rounding-button"
                                        @click="handleSelectOtherFeeType(purchaseContract.otherFundsLessPrice)">
                                        添加
                                    </el-button>
                                </div>
                            </div>

                           
                            <div v-if="purchaseContract.otherFundsLessPrice.length > 0"
                                class="amount-item other-fees-detail">
                                <div :class="{ 'readonly-mode': !editMode }">
                                    <div v-for="(fee, index) in purchaseContract.otherFundsLessPrice.otherFeeList"
                                        :key="index" class="other-fee-item">
                                        <span class="fee-name">{{ fee.otherFeeType.name }}:</span>

                                        <input-cell :width="'220px'" :readonly="!editMode"
                                            :model-value="fee.fundDouble.value" :numberMode="true"
                                            :precision="fundPrecision" @update:model-value="val => {
                                                fee.fundDouble = new CsFundDouble(val, fundPrecision);
                                                purchaseContract.calculatePriceAndQuantity();
                                            }">

                                            <el-button link size="small" @click="handleDeleteOtherFeeRowLess(fee)"
                                                style="color: #f56c6c;">
                                                删除
                                            </el-button>

                                        </input-cell>

                                    </div>
                                </div>
                            </div>
                         -->   

                            <div class="amount-item">
                                <span class="label right-align">其他费用:</span>
                                <div class="value left-align">
                                    <input-cell :width="'200px'" :readonlyWidth="'200px'" :readonly="true"
                                        :model-value="purchaseContract.otherFundsMorePrice.value.value"
                                        :numberMode="true" :precision="fundPrecision" />
                                    <el-button v-if="editMode" style="margin-left: 8px;" type="primary" size="small"
                                        class="rounding-button"
                                        @click="handleSelectOtherFeeType(purchaseContract.otherFundsMorePrice)">
                                        添加
                                    </el-button>
                                </div>
                            </div>

                            <!-- Add detailed other fees list -->
                            <div v-if="purchaseContract.otherFundsMorePrice.length > 0"
                                class="amount-item other-fees-detail">
                                <div :class="{ 'readonly-mode': !editMode }">
                                    <div v-for="(fee, index) in purchaseContract.otherFundsMorePrice.otherFeeList"
                                        :key="index" class="other-fee-item">
                                        <span class="fee-name">{{ fee.otherFeeType.name }}:</span>

                                        <input-cell :width="'220px'" :readonly="!editMode"
                                            :model-value="fee.fundDouble.value" :numberMode="true"
                                            :precision="fundPrecision" @update:model-value="val => {
                                                fee.fundDouble = new CsFundDouble(val, fundPrecision);
                                                purchaseContract.calculatePriceAndQuantity();
                                            }">

                                            <el-button link size="small" @click="handleDeleteOtherFeeRowMore(fee)"
                                                style="color: #f56c6c;">
                                                删除
                                            </el-button>

                                        </input-cell>

                                    </div>
                                </div>
                            </div>

                            <div class="amount-item">
                                <span class="label right-align">优惠:</span>
                                <div class="value left-align">
                                    <input-cell :width="'200px'" :readonly="!editMode"
                                        :model-value="purchaseContract.discount.value" :numberMode="true"
                                        :precision="fundPrecision"
                                        @update:model-value="val => purchaseContract.discount = new CsFundDouble(val, fundPrecision)">

                                        <el-button v-if="editMode" style="margin-left: 8px;" type="primary" size="small"
                                            class="rounding-button" @click="handleRounding()">
                                            抹零
                                        </el-button>

                                    </input-cell>
                                </div>
                            </div>                           

                            <div v-if="editMode" class="amount-item"
                                style="margin: 4px 0; padding-top: 0px; padding-bottom: 8px; ">
                                <span class="label right-align"
                                    style="font-size: 16px; font-weight: bold; color: #606266 ;">合计:
                                </span>
                                <span class="value left-align"
                                    style="font-size: 16px; font-weight: bold; color: #E64D4D;">
                                    {{ formatCurrency(purchaseContract.totalMount.value) }}
                                </span>
                            </div>
                        </div>
                    </el-card>
                </el-col>

                <el-col :span="12">
                    <el-card class="amount-summary-card" shadow="never">
                        <template #header>
                            <div class="card-header">
                                <div class="title-wrapper">
                                    <span class="title-text">付款信息</span>
                                </div>
                            </div>
                        </template>
                        <div class="amount-summary-content">

                            <!-- Add this section after the "贵金属信息" title -->
                            <div style="margin: 4px 0; padding-top: 0px; padding-bottom: 8px;" class="amount-item">
                                <span class="label right-align"
                                    style="font-size: 15px; font-weight: bold; color: #606266;">贵金属信息</span>
                            </div>



                            <div style="margin-left: 100px;" class="amount-item">
                                <el-table :data="purchaseContract.metalFundsPrice.selfDefFundDoubles"
                                    style="width: 360px" :show-header="true" border>
                                    <el-table-column prop="selfDefFundAccountType.name" label="名称" width="120">
                                    </el-table-column>
                                    <el-table-column label="回收" width="120">
                                        <template #default="scope">
                                            {{ formatCount(scope.row.expectCount.value) }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="兑金" width="120">
                                        <template #default="scope">
                                            {{ formatCount(scope.row.count.value) }}
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>

                            <div style="margin: 4px 0; padding-top: 0px; padding-bottom: 8px;"
                                v-if="purchaseContract.metalFundsPrice.count > 0" class="amount-item">
                                <span class="label right-align"
                                    style="font-size: 15px; font-weight: bold; color: #606266;">付款信息</span>
                            </div>

                            <div v-if="showPrePaymentHexiao" class="amount-item">
                                <span class="label right-align">存欠款冲抵:</span>
                                <value-checkbox-widget class="value left-align" :display-text="preOffsetText"
                                    :check-value="purchaseContract.enablePrePaymentOffset" :editable="editMode"
                                    width="200px"
                                    @update:check-value="val => purchaseContract.enablePrePaymentOffset = val">
                                    <span v-if="editMode">{{ "冲抵" + purchaseContract.prePaymentOffset.value }}</span>
                                </value-checkbox-widget>
                            </div>

                            <div class="amount-item">
                                <span class="label right-align">本次付款:</span>
                                <div class="value left-align">
                                    <input-cell :width="'200px'" :readonly="!editMode"
                                        :model-value="purchaseContract.payedMount.value" :numberMode="true"
                                        :precision="fundPrecision"
                                        @update:model-value="val => purchaseContract.payedMount = new CsFundDouble(val)" />
                                </div>
                            </div>

                            <div v-if="purchaseContract.payedMount.value != 0" class="amount-item">
                                <span class="label right-align">付款账户:</span>
                                <div class="value left-align" style="width: 200px;">
                                    <fund-account-select :readonly="!editMode" v-model="purchaseContract.fundAccount"
                                        prop="fundAccount" :fund-ui-action="fundUiAction" />
                                </div>
                            </div>

                            <div v-if="editMode" class="amount-item"
                                style="margin: 4px 0; padding-top: 0px; padding-bottom: 8px; ">
                                <span class="label right-align"
                                    style="font-size: 14px; font-weight: bold; color: #606266 ;">剩余应付:
                                </span>
                                <span class="value left-align"
                                    style="font-size: 14px; font-weight: bold; color: #E64D4D;">
                                    {{ formatCurrency(purchaseContract.remainAmount.value) }}
                                </span>
                            </div>

                            <div v-if="!editMode" class="amount-item">
                                <span class="label right-align">应付款:</span>
                                <span class="value left-align">{{ formatCurrency(purchaseContract.totalMount.value)
                                    }}</span>
                            </div>

                            <div v-if="!editMode" class="amount-item">
                                <span class="label right-align">实付款:</span>
                                <span class="value left-align">{{
                                    formatCurrency(purchaseContract.totalPayedMount(editMode).value)
                                    }}</span>
                            </div>
                        </div>
                    </el-card>
                </el-col>

                <el-col :span="12" class="other-info-col">
                    <!-- Other Information Group -->
                    <el-card class="other-info-card" shadow="never">
                        <template #header>
                            <div class="card-header">
                                <div class="title-wrapper">
                                    <span class="title-text">其他信息</span>
                                </div>
                            </div>
                        </template>

                        <el-descriptions v-if="!editMode" :column="1">
                            <el-descriptions-item v-if="latestUpdateInfo" label="最近更新">{{ latestUpdateInfo
                                }}</el-descriptions-item>
                            <el-descriptions-item label="制单人">{{ docMaker }}</el-descriptions-item>
                            <el-descriptions-item label="备注">
                                <div class="remark-content">{{ purchaseContract.remark || '-' }}</div>
                            </el-descriptions-item>
                        </el-descriptions>

                        <!-- 注意本处增加一个div , 不然第一个控件左对齐有问题，具体问题待查  -->
                        <div> </div>

                        <!-- 备注 -->
                        <input-widget-web class="value left-align" v-if="editMode" v-model="formData.remark" label="备注"
                            prop="remark" placeholder="请输入备注信息" :remarkMode="true" />
                    </el-card>
                </el-col>
            </el-row>

            <!-- 底部操作栏 (仅在编辑模式下显示) -->
            <bottom-bar :visible="editMode">
                <template #left>
                    <span class="doc-maker-info">制单人: {{ docMakerBottmBar }}</span>
                </template>
                <template #right>
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">提交</el-button>
                </template>
            </bottom-bar>

            <!-- 商品选择弹窗 -->
            <subcommodity-select-dialog ref="commoditySelectDialog" :basic-ui-action="basicUiAction"
                @select="handleCommoditySelect" />

            <!-- 其他费用选择弹窗 -->
            <other-fee-type-select-dialog ref="otherFeeTypeSelectDialog" :fund-ui-action="fundUiAction"
                @select="handleOtherFeeTypeSelect" />

            <order-result-dialog ref="orderResultDialog" />
        </div>
    </div>
</template>

<script>
import { PurchaseContract } from '../../public/engine/purchase/purchaseContract'
import { CommodityBatchWithTax } from '../../public/engine/sales/sales'
import { Employee } from '../../public/engine/enterpriseMgt/employee'
import { CsDouble } from '../../public/engine/common/csDouble'
import { CsFundDouble } from '../../public/engine/common/csFundDouble'
import { CommonOrderStatus } from '../../public/engine/common/docDefinition'
import { PurchaseUiAction } from '../../public/engine/uiAction/purchaseUiAction'
import { InventoryUiAction } from '../../public/engine/uiAction/inventoryUiAction'
import { Util } from '../../public/utils/util'
import { DateUtil } from '../../public/utils/dateUtil'
import { Engine } from '../../public/engine/engine'
import { ElMessage, ElMessageBox } from 'element-plus'
import { BasicUiAction } from '../../public/engine/uiAction/basicUiAction'
import { EnterpriseMgtUiAction } from '../../public/engine/uiAction/enterpriseMgtUiAction.js'
import { ActionResult, ActionResultType } from '../../public/engine/common/actionResult.js'
import InputWidgetWeb from '../../public/views/componentsWeb/InputWidgetWeb.vue'
import PartnerSelect from '../../public/views/componentsWeb/PartnerSelect.vue'
import WarehouseSelect from '../../public/views/componentsWeb/WarehouseSelect.vue'
import DateTimeSelect from '../../public/views/componentsWeb/DateTimeSelect.vue'
import EmployeeSelect from '../../public/views/componentsWeb/EmployeeSelect.vue'
import QualityInputCell from '../../public/views/componentsWeb/QualityInputCell.vue'
import ValueCheckboxWidget from '../../public/views/componentsWeb/ValueCheckboxWidget.vue'
import InputCell from '../../public/views/componentsWeb/InputCell.vue'
import SubcommoditySelectDialog from '../../views/inventory/subcommoditySelectDialog.vue'
import OtherFeeTypeSelectDialog from '../fund/otherFeeTypeSelectDialog.vue'
import BottomBar from '../../public/views/componentsWeb/BottomBar.vue'
import EventBus from '../../public/engine/ipc/eventBus'
import TabUtil from '@/plugins/tab'
import { MessageUtil } from '@/utils/MessageUtil'
import { Definition } from '../../public/engine/common/definition.js'
import FundAccountSelect from '../../public/views/componentsWeb/FundAccountSelect.vue'
import { FundUiAction } from '../../public/engine/uiAction/fundUiAction'
import { OtherFundDouble } from '../../public/engine/funds/otherFundDouble'
import { MetalPurchaseTradeMode } from '../../public/engine/common/metalDefinition.js'
import { TargetObjectPlatformType } from '../../public/engine/targetOrg/targetObject'
import orderResultDialog from '../dialog/orderResultDialog.vue'
import SubcommoditySelect from '../../public/views/componentsWeb/SubcommoditySelect.vue'
import { CommodityUiAction } from '../../public/engine/uiAction/commodityUiAction.js'
import { SubCommodityFilter, SubCommodityMetalFilterTypeEnum } from '../../public/engine/commodity/subCommodity'
import { QuestionFilled } from '@element-plus/icons-vue'
import MetalFinessInputCell from '../../public/views/componentsWeb/MetalFinessInputCell.vue'

export default {
    name: 'metalOrder',
    components: {
        InputWidgetWeb,
        PartnerSelect,
        WarehouseSelect,
        DateTimeSelect,
        EmployeeSelect,
        QualityInputCell,
        InputCell,
        SubcommoditySelectDialog,
        BottomBar,
        ValueCheckboxWidget,
        FundAccountSelect,
        OtherFeeTypeSelectDialog,
        orderResultDialog,
        SubcommoditySelect,
        QuestionFilled,
        MetalFinessInputCell,        
    },

    data() {
        return {
            purchaseContract: PurchaseContract.empty({
                operator: Engine.profile?.nickName,
                operatorId: Engine.profile?.id
            }),
            orgPurchaseContract: PurchaseContract.empty({
                operator: Engine.profile?.nickName,
                operatorId: Engine.profile?.id
            }),
            basicUiAction: new BasicUiAction(),
            purchaseUiAction: new PurchaseUiAction(),
            inventoryUiAction: new InventoryUiAction(),
            enterpriseMgtUiAction: new EnterpriseMgtUiAction(),
            loading: false,
            CommonOrderStatus,
            PurchaseContract,
            CsDouble,
            CsFundDouble,
            editMode: false,
            orderId: "",
            formData: {
                docCode: '',
                title: '',
                targetObject: null,
                warehouse: null,
                operateDate: null,
                operator: null,
                remark: '',
                updator: null,
                docMaker: null,
            },
            // 返回数据
            retValue: null,
            selectedCommodities: [],
            submitting: false, // 添加提交状态标识
            fundUiAction: new FundUiAction(),
            MetalPurchaseTradeMode,
            TargetObjectPlatformType,
            commodityUiAction: new CommodityUiAction(),
            metalSubcommodityFilter: new SubCommodityFilter({ metalType: SubCommodityMetalFilterTypeEnum.MetalRelatedOnly }),
        }
    },

    mounted() {
        this.retValue = null;
        this.orderId = (this.$route.params.id || this.$route.query.id) || "";

        if (!Util.isEmpty(this.orderId)) {
            this.loadPurchaseContractData();
        } else {
            this.editMode = true;
            this.syncFormData();
            this.fillWithEmptyCommodityLineData();
        }
    },


    beforeUnmount() {
        if (this.retValue) {
            EventBus.emit('purchaseContractUpdated', null);
            this.retValue = null;
        }
    },

    deactivated() {
        if (this.retValue) {
            EventBus.emit('purchaseContractUpdated', null)
            this.retValue = null;
        }
    },

    computed: {

        // 折后重量提示
        discountWeightHint() {
            return "1 成色 24K,折后重量 = 重量 <br>" +
                "2 成色 900-999, 折后重量 = 重量 x (成色-2) ÷ 1000 <br>" +
                "3 成色 750, 折后重量 = 重量 x (成色-2) ÷ 1000 <br>" +
                "4 成色 100-899, 折后重量 = 重量 x (成色-3) ÷ 1000 <br>" +
                "5 其他成色, 不支持"
        },

        // 折后价格提示
        discountPriceHint() {
            return "1 成色 24K,折后价格 = 金价 <br>" +
                "2 成色 900-999, 折后价格 = 金价 x (成色-2) ÷ 1000 <br>" +
                "3 成色 750, 折后价格 = 金价 x (成色-2) ÷ 1000 <br>" +
                "4 成色 700-899, 折后价格 = 金价 x (成色-3) ÷ 1000 <br>" +
                "5 成色 100-699, 折后价格 = 金价 x (成色-5) ÷ 1000 <br>" +
                "6 其他成色, 不支持"
        },

        // 模式提示
        tradeModeHint() {
            return "1 兑金结价: 影响客户存欠款，商户资金账户，应付款，旧料库存<br>" +
                "  1) 按设成色对应单价结算应付金额 <br>" +
                "  2) 影响客户存欠款: 客户存欠款 = 客户存欠款 + 本单合计剩余应付款 <br>" +
                "  3) 按折前重量产生旧料入库 <br>" +
                "<br>" +
                "2 兑金: 影响客户存欠料，旧料库存<br>" +
                "  1) 客户存欠料 = 客户存欠料 + 按折后重量<br>" +
                "  2) 按折前重量产生旧料入库 <br>" +
                "<br>" +
                "3 结价: 影响客户存欠款、存欠料，商户资金账户，应付款<br>" +
                "  1) 影响客户存欠款: 客户存欠款 = 客户存欠款 + 本单合计剩余应付款 <br>" +
                "  2) 客户存欠料 = 客户存欠料 - 折后重量 <br>" +
                "  3) 注意：需要核对是否需要指定24K"

        },


        multiStoreMode() {
            return Engine.getOrgSettings().multiStoreMode;
        },
        metalPurchaseTradeModes() {
            // Extract all modes from MetalPurchaseTradeMode except the fromCode method
            /* return Object.values(MetalPurchaseTradeMode).filter(item =>
                typeof item === 'object' && item !== null && 'code' in item && 'name' in item
            );
            */
            return [MetalPurchaseTradeMode.SettleMetal_SettlePrice, MetalPurchaseTradeMode.SettleMetal, MetalPurchaseTradeMode.SettledPrice];
        },
        latestUpdateInfo() {
            return (this.purchaseContract.updateor && this.purchaseContract.updateDate) ?
                (this.purchaseContract.updateor + "  " + DateUtil.getDayTitle(this.purchaseContract.updateDate)) : null;
        },

        docMaker() {
            return (this.purchaseContract.id && this.purchaseContract.docMaker && this.purchaseContract.recordDate) ?
                (this.purchaseContract.docMaker + "  " + DateUtil.getDayTitle(this.purchaseContract.recordDate)) : null
        },

        docMakerBottmBar() {
            return Engine.profile?.nickName.isEmpty
                ? Engine.profile?.userName
                : Engine.profile?.nickName;
        },

        fundPrecision() {
            return Definition.fundPrecision;
        },

        countPrecision() {
            return Definition.precision;
        },

        disCountRation() {
            return Definition.gConstDiscountRatePrecision;
        },

        preOffsetText() {
            //console.log("preOffsetText supplier", this.purchaseContract.prePaymentOffset.value);
            console.log("this.purchaseContract.supplierPrePaymentAmount:", this.purchaseContract.supplierPrePaymentAmount);
            console.log("this.purchaseContract.prePaymentOffset.value:", this.purchaseContract.prePaymentOffset.value);
            return this.editMode ? "欠款:" + Util.getFundString(this.purchaseContract.supplierPrePaymentAmount - this.purchaseContract.prePaymentOffset.value)
                : this.formatCurrency(this.purchaseContract.prePaymentOffset.value, true);
        },

        // 有付款金额时显示
        // 负数才是往来单位欠款，用于扣除付款
        showPrePaymentHexiao() {
            /*
            if( this.purchaseContract.totalMount.value > 0 &&
                (this.purchaseContract.supplierPrePaymentAmount + this.purchaseContract.prePaymentOffset.value < 0) ){
                return true;
            }
               */
            if (this.purchaseContract.totalMount.value > 0 &&
                this.purchaseContract.supplierPrePaymentAmount < 0 || (this.purchaseContract.prePaymentOffset.value < 0)) {
                return true;
            }

            return false;
        },

        supportMultyWarehouse() {
            return Engine.getOrgSettings().enableMultiWarehouse;
        },

    },

    methods: {

        // 更新供应商
        updateTargetObject(val) {
            this.purchaseContract.supplier = val;
        },

        // 填充空的商品信息
        fillWithEmptyCommodityLineData() {
            // 如果商品记录数量小于 4，添加空记录达到 4条
            if (this.purchaseContract.commmodityList.length < 4) {
                for (let i = this.purchaseContract.commmodityList.length; i < 4; i++) {
                    this.purchaseContract.addCommodityBatch(CommodityBatchWithTax.empty({ taxRate: 0 }));
                }
            } else {
                // 如果商品数量大于4，判断最后一个商品是否是空记录，如果是的，添加一条空记录
                if (this.purchaseContract.commmodityList[this.purchaseContract.commmodityList.length - 1].commodity == null) {
                    this.purchaseContract.addCommodityBatch(CommodityBatchWithTax.empty({ taxRate: 0 }));
                }
            }
        },

        handleModeSelect(batch, val) {
            console.log("Batch updated:", batch, val);
            batch.metalPurchaseTradeMode = MetalPurchaseTradeMode.fromCode(val);
            this.purchaseContract.calculatePriceAndQuantity();
        },

        /*
        testLog(batch){
            console.log("Batch updated:",batch);
        },
        */
        syncFormData() {
            this.formData = {
                docCode: this.purchaseContract.docCode,
                title: this.purchaseContract.title,
                targetObject: this.purchaseContract.supplier,
                warehouse: this.purchaseContract.wareHouse,
                operateDate: this.purchaseContract.operateDate,
                operator: new Employee({ id: this.purchaseContract.operatorId, name: this.purchaseContract.operator }),
                remark: this.purchaseContract.remark,
                updator: (this.purchaseContract.updateor && this.purchaseContract.updateDate) ?
                    (this.purchaseContract.updateor + "  " + DateUtil.getDayTitle(this.purchaseContract.updateDate)) : null,
                docMaker: (this.purchaseContract.id && this.purchaseContract.docMaker && this.purchaseContract.recordDate) ?
                    (this.purchaseContract.docMaker + "  " + DateUtil.getDayTitle(this.purchaseContract.recordDate)) : null,

            };
        },

        fillWithFormData() {
            this.purchaseContract.title = this.formData.title;
            this.purchaseContract.supplier = this.formData.targetObject;
            this.purchaseContract.wareHouse = this.formData.warehouse;

            // formData.operateDate 控件变更日期会转换为字符串，这里需要转换回Date对象
            if (!(this.formData.operateDate instanceof Date)) {
                this.purchaseContract.operateDate = DateUtil.strToDate(this.formData.operateDate);
            } else {
                this.purchaseContract.operateDate = this.formData.operateDate;
            }

            this.purchaseContract.setOperator({
                operator: this.formData.operator.name,
                operatorId: this.formData.operator.id
            });
            this.purchaseContract.remark = this.formData.remark;
        },

        handleDeleteRow(row) {
            this.purchaseContract.removeCommodityBatch(row);
            // ElMessage.success('商品已删除');
        },

        // 抹零
        handleRounding() {
            this.purchaseContract.setDiscountValueWithSmallChange();
        },

        // 商品选择 items 类型 SubCommodityInventorySumData
        handleCommoditySelect(items) {
            if (items && items.length > 0) {
                for (let commodity of items) {
                    // 检查商品是否已存在
                    /*
                    const exists = this.purchaseContract.commmodityList.some(
                        item => item.commodity.id === commodity.subCommodity.id
                    );
                    */

                    let exists = false;

                    if (!exists) {
                        let batch = new CommodityBatchWithTax({
                            commodity: commodity.subCommodity,
                            count: new CsDouble(1),
                            availableCount: commodity.availableCount,
                            inventoryCount: commodity.totalInventoryCount,
                            batchPrice: commodity.subCommodity.purchasePrice,
                            singlePrice: commodity.subCommodity.purchasePrice,
                            referPrice: commodity.subCommodity.purchasePrice,
                            metalPurchaseTradeMode: MetalPurchaseTradeMode.SettleMetal_SettlePrice,
                        });

                        if (this.purchaseContract.isSupportDetailWithTax) {
                            this.purchaseContract.addCommodityBatch(batch);
                        } else {
                            this.purchaseContract.addCommodityBatch(CommodityBatchWithTax.fromCommodityBatchWithTaxSimpleMode(
                                batch));
                        }


                    }

                }
            }
        },

        // 其他类型费用选择
        handleOtherFeeTypeSelect(items, otherFeePrice) {
            console.log('handleOtherFeeTypeSelect', items);

            for (let i = 0; i < items.length; i++) {
                otherFeePrice.addOtherFeeFundAccount(new OtherFundDouble(items[i], CsFundDouble.zero()));
            }

        },

        handleCopy() {
            this.purchaseContract.resetForCopy();
            this.editMode = true;
            MessageUtil.showSuccessMsg("复制完成");
        },

        handlePrint() {
            // 在新标签页中打开相同页面           

            // Create a new window/tab for printing
            const printWindow = window.open('', '_blank');

            // Generate HTML content for printing
            const printContent = this.generatePrintContent();

            // Write content to the new window
            printWindow.document.write(printContent);
            printWindow.document.close();

            // Print after content is loaded
            /*
            printWindow.onload = function () {
                printWindow.print();
            };
            */
        },

        handleEdit() {
            this.editMode = true;
        },

        async handleDelete() {
            if (Util.isEmpty(this.purchaseContract.id)) {
                TabUtil.closePage();
            } else {
                try {
                    await ElMessageBox.confirm("确定要删除该回购单据吗？", "删除确认", {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    });

                    this.submitting = true;

                    let delResult = await this.purchaseUiAction.removePurchaseOrder({
                        orderId: this.purchaseContract.id,
                        docType: this.purchaseContract.docType
                    });

                    if (delResult == null) {
                        this.retValue = new ActionResult({ type: ActionResultType.Del });
                        MessageUtil.showSuccessMsg("删除成功");
                        TabUtil.closePage();
                    }
                } catch (error) {
                    if (error !== 'cancel') {
                        console.error("purchaseContractDetailPage handleDelete error:", error);
                        ElMessage.error("删除操作失败");
                    }
                } finally {
                    this.submitting = false;
                }
            }
        },

        handleAddCommodity() {
            if (this.formData.warehouse == null ||
                this.formData.warehouse.id == null ||
                Util.isEmpty(this.formData.warehouse.id)) {
                MessageUtil.showWarningMsg("请先选择仓库");
                return;
            }

            this.$refs.commoditySelectDialog.open(
                this.purchaseContract.commmodityList.map(item => ({
                    commodity: item.commodity
                })),
                {
                    warehouse: this.formData.warehouse
                }
            );
        },

        // 添加其他费用
        handleSelectOtherFeeType(otherPrice) {
            this.$refs.otherFeeTypeSelectDialog.open([], otherPrice);
        },

        // 删除其他费用项
        handleDeleteOtherFeeRowLess(item) {
            this.purchaseContract.otherFundsLessPrice.removeOtherFeeFundAccount(item);
            this.purchaseContract.calculatePriceAndQuantity();
        },

        // 删除其他费用项
        handleDeleteOtherFeeRowMore(item) {
            this.purchaseContract.otherFundsMorePrice.removeOtherFeeFundAccount(item);
            this.purchaseContract.calculatePriceAndQuantity();
        },


        handleSelectionChange(selection) {
            this.selectedCommodities = selection;
        },

        handleDeleteSelectedCommodities() {
            if (this.selectedCommodities.length === 0) {
                ElMessage.warning('请至少选择一个商品进行删除');
                return;
            }

            // 删除选中的商品
            this.selectedCommodities.forEach(commodity => {
                this.purchaseContract.removeCommodityBatch(commodity);
            });

            // 清空选中
            this.selectedCommodities = [];
        },

        // 取消编辑
        handleCancel() {
            this.purchaseContract = PurchaseContract.clone(this.orgPurchaseContract);
            this.editMode = false;
        },

        async handleSubmit() {

            try {
                // First validate the form
                await this.$refs.ruleFormRef.validate();
                // 验证表单
                const validationError = this.purchaseContract.validateOrder();
                if (validationError) {

                    if (validationError.errorMsg) {

                        if (validationError.msgBoxConfirm) {
                            try {
                                await ElMessageBox.confirm(
                                    validationError.errorMsg,
                                    '信息错误',
                                    {
                                        confirmButtonText: '确认',
                                        type: 'error'
                                    }
                                );

                                // 错误信息直接返回
                                return;

                            } catch (confirmError) {
                                // User cancelled
                                this.submitting = false;
                                return;
                            }
                        }
                        else {

                            ElMessage.error(validationError.errorMsg);
                            return;
                        }
                    }
                    else if (validationError.warningMsg) {
                        if (validationError.msgBoxConfirm) {
                            try {
                                await ElMessageBox.confirm(
                                    validationError.warningMsg,
                                    '确认提交',
                                    {
                                        confirmButtonText: '确认',
                                        cancelButtonText: '取消',
                                        type: 'warning'
                                    }
                                );

                            } catch (confirmError) {
                                // User cancelled
                                this.submitting = false;
                                return;
                            }
                        }
                        else {

                            ElMessage.error("validationError.errorMsg");
                            return;
                        }
                    }


                }

                this.submitting = true;
                this.fillWithFormData();
                //  console.log('提交回购单数据', this.purchaseContract.toJson());
                //   ElMessage.error("校验测试，暂不提交!");
                //  return;

                const orderResult = await this.purchaseUiAction.updateOrCreatePurchaseContract(this.purchaseContract, true);

                if (orderResult) {
                    if (Util.isEmpty(this.purchaseContract.id)) {
                        this.retValue = new ActionResult({ type: ActionResultType.New });
                    } else {
                        this.retValue = new ActionResult({ type: ActionResultType.UpdateCommon });
                    }
                }

                if (orderResult) {
                    // 刷新订单页面
                    ElMessage.success("提交保存成功");
                    this.orderId = orderResult.id;
                    this.editMode = false;
                    this.loadPurchaseContractData();

                    // 显示结果
                    this.$refs.orderResultDialog.open(orderResult);
                }
            } catch (error) {
                console.error('保存失败', error);
                ElMessage.error("保存失败");
            } finally {
                this.submitting = false;
            }
        },

        async loadPurchaseContractData() {
            try {
                this.loading = true;
                const res = await this.purchaseUiAction.getPurchaseDetailInfo(this.orderId);

                if (res) {
                    this.purchaseContract = res;
                    this.orgPurchaseContract = PurchaseContract.clone(res);
                    this.purchaseContract.orderBeforeEdit = this.orgPurchaseContract;
                    this.syncFormData();
                    this.fillWithEmptyCommodityLineData();
                } else {
                    ElMessage.error('获取回购单详情失败');
                }
            } catch (error) {
                console.error('加载回购单数据失败:', error);
                ElMessage.error('加载回购单数据失败');
            } finally {
                this.loading = false;
            }
        },

        formatCount(value, withSignal = false) {
            return Util.getCountString(value, null, { withPrePositiveNegtiveSignal: withSignal });
        },

        formatCurrency(value, readOnlyZeroDashLine = false) {

            return Util.getFundString(value, { zeroDashLine: readOnlyZeroDashLine && !this.editMode });
        },

        formateDate(date) {
            return DateUtil.formatDate(date, 'yyyy-MM-dd HH:mm');
        },

        generatePrintContent() {
            // Create a printable version of the purchase contract details
            return `
<!DOCTYPE html>
<html>
<head>
  <title>回购单据 - ${this.purchaseContract.docCode}</title>
  <style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        color: #333;
        line-height: 1.6;
        padding: 20px;
        min-height: 100vh;
    }

    .container {
        max-width: 1000px;
        margin: 20px auto;
        background: white;
        padding: 30px;
        border-radius: 12px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);

        position: relative;
    }

    .header {
        margin-bottom: 25px;
        border-bottom: 1px solid #bec5cc;
        padding-bottom: 15px;
    }

    .header-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 2px;
    }

    .company-name {
        font-size: 22px;
        font-weight: bold;
        color: #2c3e50;
        flex: 1;
    }

    .document-title {
        text-align: center;
        font-size: 28px;
        font-weight: bold;
        color: #2c3e50;
        flex: 2;
    }

    .document-code {
        text-align: right;
        font-size: 16px;
        color: #2c3e50;
        flex: 1;
    }

    .info-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .department {
        font-size: 16px;
        flex: 1;
    }

    .customer-info {
        text-align: center;
        font-size: 16px;
        flex: 2;
    }

    .date {
        text-align: right;
        font-size: 16px;
        flex: 1;
    }

    .info-table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 25px;
    }

    .info-table td {
        padding: 12px;
        border: 1px solid #ddd;
    }

    .items-table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 5px;
        box-shadow: 0 2px 2px rgba(0, 0, 0, 0.1);
    }

    .items-table th,
    .items-table td {
        border: 1px solid #ddd;
        padding: 2px;
        text-align: center;
    }

    .items-table th {       
        font-weight: 600;
    }

    .items-table tr:nth-child(even) {
        background-color: #f9f9f9;
    }

    .items-table tr:hover {
        background-color: #f1f9ff;
    }

    .summary-inline {
        display: flex;
        justify-content: flex-end;
        gap: 20px;
        margin-bottom: 5px;
        padding: 5px;
        border-radius: 5px;
    }

    .summary-item .label {
        font-weight: 600;
        margin-right: 5px;
    }

    .summary-item .minLabel {
        font-weight: 500;
        margin-right: 5px;
    }

    .summary-item .value.total {
        color: #2c3e50;
        font-weight: bold;
    }

    @media (max-width: 768px) {
        .summary-inline {
            flex-direction: column;
            align-items: flex-end;
        }
    }

    .text-right {
        text-align: right;
        font-weight: 600;
    }

    .total-row {
        background-color: #eaf7ff;
        font-weight: bold;
    }

    .remark-section {
        padding: 5px;
        border-top: 1px solid #bec5cc;
        border-bottom: 1px solid #bec5cc;
    }

    .footer-section {
        display: flex;
        justify-content: space-between;
        margin-top: 5px;
        border-bottom: 1px solid #bec5cc;
    }

    .declaration {
        flex: 2;
        padding: 5px 15px 15px 15px;
        border-radius: 8px;
        font-size: 14px;
    }

    .declaration-title {
        display: inline;
        font-size: 14px;
    }

    .declaration-content {
        margin-top: 1px;
        margin-left: 20px;
        line-height: 1.1;
        font-size: 14px;
    }

    .declaration-line {
        display: flex;
        margin-bottom: 2px;
        font-size: 14px;
    }

    .declaration-number {
        min-width: 15px;
        font-weight: 500;
        font-size: 14px;
    }

    .qr-code {
        flex: 1;
        text-align: center;
        padding: 2px;
    }

    .qr-code img {
        width: 100px;
        height: 100px;
        border: 1px solid #ddd;
        border-radius: 5px;
    }

    .qr-code p {
        margin-top: 0px;
        font-size: 12px;
        color: #666;
    }

    .address-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 0px;
        padding: 0px 0;

    }

    .address-text {
        font-size: 14px;
        font-weight: 500;
    }

    .contact-name {
        font-size: 14px;
    }

    .additional-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 0px;
        padding: 0px 0;
        font-size: 13px;
    }

    .website {
        flex: 1;
        text-align: left;
    }

    .customer-id {
        flex: 1;
        text-align: center;
    }

    .phone {
        flex: 1;
        text-align: right;
    }

    .footer-operator {
        display: flex;
        justify-content: center;
        margin-top: 10px;
        padding: 0px 0;            
    }

    .document-info {
        display: flex;
        justify-content: space-between;
        width: 100%;           
        align-items: center;
        font-size: 14px;
    }

    .document-info span {
        flex: 1;
        text-align: center;
        padding: 0 10px;
        white-space: nowrap;
    }

    .btn {
        padding: 12px 25px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-weight: 600;
        transition: all 0.3s ease;
    }

    .btn-print {
        background: linear-gradient(to right, #2c3e50, #4a6491);
        color: white;
    }

    .btn-print:hover {
        background: linear-gradient(to right, #1a2530, #3a5078);
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    .btn-download {
        background: linear-gradient(to right, #3498db, #2c3e50);
        color: white;
    }

    .btn-download:hover {
        background: linear-gradient(to right, #2980b9, #1a2530);
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    .button-group {
        display: flex;
        justify-content: center;
        gap: 15px;
        margin-top: 10px;
    }

    @media print {
        body {
            background-color: white;
            padding: 0;
        }

        .container {
            box-shadow: none;
            padding: 5px 15px 5px 15px;
        }

        .btn-print {
            display: none !important;
        }
    }

    @media (max-width: 768px) {
        .header-row,
        .info-row {
            flex-direction: column;
            text-align: center;
            gap: 10px;
        }

        .company-name,
        .document-title,
        .document-code,
        .department,
        .customer-info,
        .date {
            text-align: center;
            width: 100%;
        }

        .summary-table {
            width: 100%;
        }

        .document-title {
            font-size: 24px;
            order: -1;
        }

        .footer-section {
            flex-direction: column;
        }

        .qr-code {
            margin-top: 0px;
            order: 2;
        }

        .additional-info {
            flex-direction: column;
            gap: 5px;
            text-align: center;
        }

        .website,
        .customer-id,
        .phone {
            text-align: center;
            width: 100%;
        }

        .document-info {
            flex-direction: column;
            gap: 8px;
        }

        .document-info span {
            width: 100%;
            text-align: center;
        }

        .button-group {
            margin-top: 15px;
        }
    }
  </style>
</head>
<body>
  <div class="container">
    <button class="btn btn-print" onclick="window.print()" style="position: absolute; top: 30px; right: -100px; z-index: 100;">打印</button>
    <div class="header">
      <!-- 第一行：公司名称 - 标题 - 单据编号 -->
      <div class="header-row">
        <div class="department">深圳市恒泰珠宝有限公司</div>
        <div class="document-title">合记结算单</div>
        <div class="document-code">单号: ${this.purchaseContract.docCode}</div>
      </div>

      <!-- 第二行：部门 - 客户信息 - 日期 -->
      <div class="info-row">
        <div class="department">部门: 揭阳</div>
        <div class="customer-info">客户名称: ${this.purchaseContract.supplier?.name || ''}</div>
        <div class="date">日期: ${this.formateDate(this.purchaseContract.operateDate)}</div>
      </div>
    </div>
    
    <table class="items-table">
      <thead>
        <tr>
          <th>序号</th>
          <th>品名</th>         
          <th>重量(g)</th>
          <th>成色</th>
          <th>折后重量(g)</th>
          <th>单价(元/g)</th>
          <th>应付金额(元)</th>
        </tr>
      </thead>
      <tbody>
        ${this.purchaseContract.commmodityList.map((item, index) => `
        <tr>
          <td>${index + 1}</td>
          <td>${item.commodity?.standard || ''}</td>
          <td>${ item.commodity == null ? "":item.count?.value.toFixed(2) || '0.00'}</td>
          <td>${ item.commodity == null ? "":( item.discount?.value == 100 ? "24K": (item.discount?.value || 0) * 10)}</td>
          <td>${ (item.commodity == null || 
              item.metalPurchaseTradeMode?.code === MetalPurchaseTradeMode.SettledPrice.code ||
              item.metalPurchaseTradeMode?.code === MetalPurchaseTradeMode.SettleMetal_SettlePrice.code)
              ? "":item.countAfterDiscount?.value.toFixed(2) || '0.00'}</td>
          <td>${ item.commodity == null || item.metalPurchaseTradeMode?.code === MetalPurchaseTradeMode.SettleMetal.code ? "":item.singlePriceAfterTax?.value.toFixed(2) || '--'}</td>
          <td>${ item.commodity == null || item.metalPurchaseTradeMode?.code === MetalPurchaseTradeMode.SettleMetal.code ? "":item.batchPriceWithTax?.value.toFixed(2) || '--'}</td>
        </tr>
        `).join('')}
      </tbody>
    </table>

    <div class="summary-inline">
      <div class="summary-item">
        <span class="minLabel">应付:</span>
        <span class="value">${this.formatCurrency(this.purchaseContract.commodityPriceWithTax?.value )}</span>
      </div>

    ${this.purchaseContract.otherFundsMorePrice && this.purchaseContract.otherFundsMorePrice.otherFeeList && this.purchaseContract.otherFundsMorePrice.otherFeeList.length > 0 ? 
        this.purchaseContract.otherFundsMorePrice.otherFeeList.map(fee => `
        <div class="summary-item">
          <span class="minLabel">${fee.otherFeeType?.name || '其他费用'}:</span>
          <span class="value">${this.formatCurrency(fee.fundDouble?.value || 0)}</span>
        </div>
        `).join('') : ''}

      ${(this.purchaseContract.discount?.value !== 0) ? `
      <div class="summary-item">
        <span class="minLabel">抹零:</span>
        <span class="value">${this.formatCurrency(this.purchaseContract.discount?.value )}</span>
      </div>
      ` : ''}
      
      ${(this.purchaseContract.prePaymentOffset?.value !== 0) ? `
      <div class="summary-item">
        <span class="minLabel">欠款抵扣:</span>
        <span class="value">${this.formatCurrency(this.purchaseContract.prePaymentOffset?.value )}</span>
      </div>
      ` : ''}
      <div class="summary-item">
        <span class="label">合计:</span>
        <span class="value total">${this.formatCurrency(this.purchaseContract.payableMount.value )}</span>
      </div>
    </div>

    <div class="remark-section">
      <p><strong>备注:</strong> ${this.purchaseContract.remark || ''}</p>
    </div>

    <div class="footer-section">
      <div class="declaration">
        <p>
          <span class="declaration-title">声明:</span>
          <span>1. 以上货品价格以上海交易所实时价格参考为标准;</span>
        </p>
        <div class="declaration-content">
          <div class="declaration-line">
            <span class="declaration-number"></span>
            <span>2. 客户承诺以上物品物料款项是合理合法所有;</span>
          </div>
          <div class="declaration-line">
            <span class="declaration-number"></span>
            <span>3. 此单据是双方认同有效的凭证。</span>
          </div>
        </div>

        <div class="address-info">
          <span class="address-text">地址: 揭阳市揭东区富经桥恒富花园8栋15</span>
          <span class="contact-name">联系人: 郭先生</span>
        </div>

        <div class="additional-info">
          <div class="website">行情网站: www.hjzb999.com</div>
          <div class="customer-id">客户信息: </div>
          <div class="phone">联系电话: 18688068055</div>
        </div>
      </div>

      <div class="qr-code">
        <img src="https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=https://www.example.com" alt="二维码">
      </div>
    </div>

    <div class="footer-operator">
      <div class="document-info">
        <span>制单: ${this.purchaseContract.docMaker || ''}</span>
        <span>复核: ${this.purchaseContract.operator || ''}</span>
        <span>联系电话: 1333333333</span>
        <span>顾客签名: ___________</span>
      </div>
    </div>
  </div>
</body>
</html>`
;
        }


    }
}
</script>

<style scoped>
.summary-row {
    margin-bottom: 16px;
    display: flex;
    align-items: stretch;
}

.summary-row .el-col {
    display: flex;
    flex-direction: column;
}

.summary-row .el-card {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.summary-row .el-card .el-card__body {
    flex: 1;
    display: flex;
    flex-direction: column;
}

/* For the other info card specifically, we need to make its content stretch */
.other-info-card .el-card__body>*:first-child {
    flex: 1;
    display: flex;
    flex-direction: column;
}

/* Add these styles to the existing ones */
.amount-summary-content {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.amount-item {
    display: flex;
    align-items: center;
}

.amount-item .label.right-align {
    text-align: right;
    flex: 0 0 100px;
    /* Fixed width for labels */
    color: #606266;
    margin-right: 12px;
    font-size: 13px;
}

.amount-item .value.left-align {
    text-align: left;
    flex: 1;
    /* Take remaining space 
  font-weight: bold;
  */
    font-size: 13px;
}

.amount-item .total-amount .value.left-align {
    color: #E64D4D;
    font-size: 16px;
}

.purchase-contract-detail-container {
    padding: 16px;
    padding-bottom: 80px;
    /* 留出bottom bar的空间 */
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.action-buttons {
    display: flex;
    gap: 12px;
    margin-bottom: 0px;
    padding: 0 16px;
}

.title-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
}

.summary-container {
    flex: 1;
    min-width: 300px;
    display: flex;
    align-items: center;
    gap: 12px;
}

.total-info {
    color: #606266;
    font-size: 14px;
    white-space: nowrap;
}

.store-name {
    font-size: 12px;
    color: #606266;
}

.title-text {
    font-size: 16px;
    font-weight: bold;
}

.status-tag {
    margin-left: 12px;
}

.commodity-image {
    width: 40px;
    height: 40px;
    margin-right: 12px;
}

.remark-content {
    white-space: pre-wrap;
    word-break: break-all;
}

.info-card,
.items-card,
.amount-summary-card,
.other-info-card {
    margin-bottom: 16px;
    border-radius: 8px;
}

.amount-item {
    display: flex;
    justify-content: space-between;
    padding: 0px 0;
}

.amount-item .label {
    color: #606266;
}

.amount-item .value {
    font-weight: bold;
}

.total-amount .value {
    color: #E64D4D;
    font-size: 16px;
}

.other-fees-detail {
    flex-direction: column;
    align-items: flex-start;
}

.other-fees-list {
    width: 100%;
    margin-top: 0px;
    padding-top: 0px;

    /* border-top: 1px solid #ebeef5; */
}

.readonly-mode .other-fees-list {
    width: 400px;
}

.other-fee-item {
    display: flex;
    justify-content: space-between;
    width: 100%;
    padding: 4px 0;
    padding-left: 110px;
    font-size: 12px;
}

.fee-name {
    width: 50px;
    color: #606266;
}

.fee-value {
    font-weight: bold;
    color: #333;
}
</style>